/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.service.impl;

import me.zhengjie.dto.sqlServer.Storage;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.StorageRepository;
import me.zhengjie.service.StorageService;
import me.zhengjie.service.dto.StorageDto;
import me.zhengjie.service.dto.StorageQueryCriteria;
import me.zhengjie.service.mapper.StorageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author zhangYY
* @date 2024-01-12
**/
@Service
@Transactional
@RequiredArgsConstructor
public class StorageServiceImpl implements StorageService {

    private final StorageRepository storageRepository;
    private final StorageMapper storageMapper;

    @Override
    public PageResult<StorageDto> queryAll(StorageQueryCriteria criteria, Pageable pageable){
        Page<Storage> page = storageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(storageMapper::toDto));
    }

    @Override
    public List<StorageDto> queryAll(StorageQueryCriteria criteria){
        return storageMapper.toDto(storageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public StorageDto findById(Integer id) {
        Storage storage = storageRepository.findById(id).orElseGet(Storage::new);
        ValidationUtil.isNull(storage.getId(),"Storage","id",id);
        return storageMapper.toDto(storage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Storage resources) {
        if(storageRepository.findByStorageCode(resources.getStorageCode()) != null){
            throw new EntityExistException(Storage.class,"storage_code",resources.getStorageCode());
        }
        storageRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Storage resources) {
        Storage storage = storageRepository.findById(resources.getId()).orElseGet(Storage::new);
        ValidationUtil.isNull( storage.getId(),"Storage","id",resources.getId());
        Storage storage1 = null;
        storage1 = storageRepository.findByStorageCode(resources.getStorageCode());
        if(storage1 != null && !storage1.getId().equals(storage.getId())){
            throw new EntityExistException(Storage.class,"storage_code",resources.getStorageCode());
        }
        storage.copy(resources);
        storageRepository.save(storage);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            storageRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<StorageDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StorageDto storage : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("储位编码", storage.getStorageCode());
            map.put("载盘id", storage.getPalletId());
            map.put("逻辑地址类型", storage.getLogicalAddressType());
            map.put("库区编码", storage.getZoneCode());
            map.put("巷道号", storage.getAisle());
            map.put("层号", storage.getLayer());
            map.put("排号", storage.getRow());
            map.put("列号", storage.getColumn());
            map.put("货位状态(0-无货1-有货)", storage.getLocationInventoryStatus());
            map.put("是否启用(0-禁用 1-启用)", storage.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Storage findSuitableStorage(String areaCode) {
        List<Storage> storages = storageRepository.findStorageByAreaIdAndStatus(areaCode);
        if(storages.isEmpty()){
            return null;
        }
        // 从符合条件的集合中随机选一个储位
        return storages.get(new Random().nextInt(storages.size()));
    }

    @Override
    public void updateStorage(Storage storage) {
        storageRepository.save(storage);
    }

    @Override
    public List<Storage> findStorageByWareHouseArea(String area) {
        return storageRepository.findStoragesByZoneCode(area);
    }

    @Override
    public List<Storage> findStoragesByRowAndWareHouseAreaAndLayerOrderByColumn(int row, String area, int layer) {
        return storageRepository.findStoragesByRowAndZoneCodeAndLayerOrderByColumnDesc(row, area,layer);
    }

    @Override
    public String findStorageCodeById(Integer Id) {
        return storageRepository.findCodeById(Id);
    }

    @Override
    @Transactional
    public void lockStorage(Integer storageId) {
        storageRepository.updateStorageStatusById(storageId);
    }



    @Override
    public List<Storage> findAllOpenStorages() {
        return storageRepository.findAllOpenStorage();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cleanStorage(String storageCode) {
        storageRepository.updateStorageInventoryStatus(storageCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int openStorage(String storageCode) {
        return storageRepository.updateStorageStatus(storageCode);
    }

    @Override
    public Storage findStorageByStorageCode(String storageCode) {
        return storageRepository.findByStorageCode(storageCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int finishInBound(Integer palletId, String storageCode) {
        return storageRepository.updatePalletCode(palletId,storageCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStorageStatusById(Integer status, Integer storageId) {
        return storageRepository.changeStorageStatusById(status, storageId);
    }
}